package com.feidu.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.Display;
import android.widget.ImageView;

/**
 * 添加处理过的图片到imageview视图
 * @author MV
 *
 */
public class PictureUtils {

	/**
	 * 将图片缩放到设备默认的显示尺寸
	 * @return
	 */
	public static BitmapDrawable getScaleDrawable(Activity a,String path){
		
		Display display = a.getWindowManager().getDefaultDisplay();
		
		float destWidth = display.getWidth();
		float destHeight= display.getHeight();
		//读取磁盘上的图像的尺寸
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		
		float srcWidth = options.outWidth;
		float srcHeight = options.outHeight;
		
		int inSampleSize = 1;
		if (srcHeight > destHeight || srcWidth > destWidth) {
			
			if (srcWidth > srcHeight) {
				
				inSampleSize = Math.round(srcHeight / destHeight);
				
			}else {
				
				inSampleSize = Math.round(srcWidth / destWidth);
			}
			
			options = new BitmapFactory.Options();
			options.inSampleSize = inSampleSize;
		}
		
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);
		return new BitmapDrawable(a.getResources(), bitmap);
	}
	/**
	 * 清理工作
	 * 卸载图片
	 * @param imageView
	 */
	public static void cleanImageView(ImageView imageView){
		
		if (!(imageView.getDrawable() instanceof BitmapDrawable)) {
			
			return;
		}
		
		BitmapDrawable b = (BitmapDrawable) imageView.getDrawable();
		//Bitmap.recycle()方法释放了bitmap占用的原始存储空间
		//如果不主动调用recycle()方法释放内存，占用的内存也会被清理。但是，它是在将来某个
		//时点在finalizer中清理，而不是在bitmap自身的垃圾回收时清理。这意味着很可能在finalizer调用
		//之前，应用已经耗尽了内存资源。
		b.getBitmap().recycle();
		imageView.setImageDrawable(null);
	}
}
